/*
 * @Description:
 * @Author: 胡涛
 * @Date: 2023-09-05 23:23:06
 * @LastEditors: 胡涛
 * @LastEditTime: 2023-10-19 23:09:32
 */
import { enums } from "./enums";
import type { IEnumItem } from "@/types";

/**
 * 获取枚举下拉选项
 * @param nameOrData
 */
const getEnumOptions = (nameOrData: string | IEnumItem) => {
  let data =
    typeof nameOrData == "string"
      ? (enums[nameOrData] as IEnumItem)
      : nameOrData;
  return data.items.map((x) => {
    return { label: x.description, value: x.value };
  });
};

/**
 * 枚举名称
 * @param nameOrData
 * @param value
 */
const enumName = (
  nameOrData: string | IEnumItem,
  value: number,
  flag?: boolean
) => {
  let data =
    typeof nameOrData == "string"
      ? (enums[nameOrData] as IEnumItem)
      : nameOrData;
  if (flag) {
    return data.items
      .filter((x) => (value & x.value) == x.value)
      .map((x) => x.description)
      .join(",");
  } else {
    return data.items.find((x) => x.value === value)?.description || "";
  }
};

/**
 * 合并枚举
 * @param name
 * @param values
 * @returns
 */
const enumMarge = (name: string, values: Array<number>): number => {
  let data = enums[name] as IEnumItem;
  if (data?.items) {
    let num = 0;
    data.items
      .filter((x) => values.findIndex((val) => val === x.value) !== -1)
      .map((x) => {
        num += x.value;
      });
    return num;
  } else {
    let num = 0;
    values.map((x) => {
      num += x;
    });
    return num;
  }
};

/**
 * 拆分枚举值
 */
const enumSplit = (name: string, value: number): Array<number> => {
  let data = enums[name] as IEnumItem;
  if (data?.items) {
    return data.items
      .filter((x) => (value & x.value) == x.value)
      .map((x) => x.value);
  } else {
    return [value];
  }
};

export { getEnumOptions, enumMarge, enumName, enumSplit };
